package cn.tedu.circle.passport.service.impl;

import cn.tedu.circle.passport.dao.persist.repository.IUserRepository;
import cn.tedu.circle.passport.pojo.param.UserLoginInfoParam;
import cn.tedu.circle.passport.pojo.vo.UserLoginInfoVO;
import cn.tedu.circle.passport.pojo.vo.UserLoginResultVO;
import cn.tedu.circle.passport.service.IUserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserSeviceImpl implements IUserService {

    @Autowired
    private IUserRepository userRepository;

    @Override
    public UserLoginResultVO login(UserLoginInfoParam userLoginInfoParam) {
        // 从参数中获取用户名
        // 调用Repository根据用户名查询用户信息
        // 判断查询结果是否为nu11
        // 是: 抛出异常《unauthorized) : 用户名或密码错误

        // 判断查询结果中enable是否为0
        // 足: 抛出异常 (unauthorized_disabled): 账号被禁用
        // 注意:由于还没讲密码加密的问题，所以，你应该先将数库中的账号密码先改成明文的密码，便于接下来使用equa1sO)进行对比
        // 从参数中获取密码
        // 到断查询结果中的密码与参数密码是否不匹配(暂时使用equalsO方法)
        // 是: 抛出异常(unauthorized) : 用户名或密码借误

        UserLoginInfoVO queryResult = userRepository.getLoginInfoByUsername(userLoginInfoParam.getUsername());
        if (queryResult == null) {
            throw new cn.tedu.tmall.common.ex.ServiceException(cn.tedu.tmall.common.enumerator.ServiceCode.ERROR_UNAUTHORIZED,"用户名或密码错误！");
        }
        if (queryResult.getEnable() == 0) {
            throw new cn.tedu.tmall.common.ex.ServiceException(cn.tedu.tmall.common.enumerator.ServiceCode.ERROR_UNAUTHORIZED_DISABLED,"账号被禁用！");
        }
        if(!queryResult.getPassword().equals(userLoginInfoParam.getPassword())){
            throw new cn.tedu.tmall.common.ex.ServiceException(cn.tedu.tmall.common.enumerator.ServiceCode.ERROR_UNAUTHORIZED,"用户名或密码错误！");
        }




/*        //创建当事人对象
        CurrentPrincipal principal = new CurrentPrincipal();
        principal.setId(queryResult.getId());
        principal.setUsername(queryResult.getUsername());

        //准备权限列表
        ArrayList<SimpleGrantedAuthority> authorities = new ArrayList<>();
        List<String> permissions = queryResult.getPermissions();
        for (String permission : permissions) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }

        // 向SecurityContext中存入有效的Authentication
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                principal, null, authorities);
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authentication);
*/

        String secretKey = "123456789abcdefghijklmnopqrstuvwxyz";

        Map<String, Object> claims = new HashMap<>();
        claims.put("id",queryResult.getId());
        claims.put("username",queryResult.getUsername());
        String jwt = Jwts.builder()
                //Header
                .setHeaderParam("alg","HS256")
                .setHeaderParam("typ","JWT")
                //Payload
                .setClaims(claims)
                //Verify Signature
                .signWith(SignatureAlgorithm.HS256,secretKey)
                //完成
                .compact();

        UserLoginResultVO loginResult = new UserLoginResultVO();
        BeanUtils.copyProperties(queryResult,loginResult);
        loginResult.setToken(jwt);
        return loginResult;
    }
}
